<script setup lang="ts" name="auth">
import { showToast } from 'vant';
import { getUrlParam, getAuthUrl, navigateTo } from '@/utils';
import api from '@/api';
import { onActivated, onMounted, ref } from 'vue';
import store from '@/utils/store';

const showBtn = ref(false);

onMounted(async () => {
    showBtn.value = !!store.get('JUMP_AUTH');
    const jsCode = getUrlParam('code');
    if (jsCode) {
        try {
            const { code, message, data } = await api.fetchPost(
                'officialAuthV2',
                { jsCode },
                { isLoading: true, hasErr: true }
            );
            if (code === 0) {
                store.set('USERINFO', data);
                store.set('LOGIN_SCOPE', 'userinfo');
                history.go(-3);
            } else {
                showToast(message);
            }
        } catch (err) {
            console.log(err);
            showToast('授权失败');
        }
    }
});

onActivated(() => {
    showBtn.value = !!store.get('JUMP_AUTH');
});

const onAuth = () => {
    const authUrl = getAuthUrl('/auth', 'snsapi_userinfo');
    setTimeout(() => {
        showBtn.value = true;
    }, 3000)
    store.set('JUMP_AUTH', true);
    navigateTo(authUrl, { routerType: 'replace', isBlank: true });
};

// 跳转授权
const onJumpAuth = async () => {
    api.fetchPost('skipAuth').then(() => {
        const userInfo = store.get('USERINFO');
        store.set('USERINFO', {
            ...userInfo,
            userStatus: 'AUTHED'
        });
        store.set('LOGIN_SCOPE', 'userinfo');
        setTimeout(() => {
            history.go(-1);
        }, 50);
    });
};
</script>

<template>
    <div class="main">
        <img
            class="weichat"
            src=""
        />
        <p class="title">请授权头像昵称</p>
        <p class="desc">便于商家识别付款人，发货、售后更高效</p>
        <div class="btn-box">
            <van-button class="btn btn-primary" @click="onAuth">去授权</van-button>
            <van-button class="btn btn-secondary" v-if="showBtn" @click="onJumpAuth"
                >跳过授权</van-button
            >
        </div>
    </div>
</template>

<style lang="less" scoped>
@import '../../styles/variables.less';
.main {
    background-color: @white;
    text-align: center;
    height: 100vh;
    overflow: hidden;
}
.weichat {
    width: 64px;
    height: 64px;
    display: block;
    margin: 100px auto 16px;
}
.title {
    font-size: 22px;
    font-weight: 600;
    margin-bottom: 8px;
}
.desc {
    font-size: 14px;
    font-weight: 400;
    margin-bottom: 60px;
}
.btn-box {
    display: flex;
    align-items: center;
    flex-direction: column;
    width: 100%;
}

.btn {
    font-size: 17px;
    font-weight: 500;
    width: 184px;
    height: 40px;
    line-height: 40px;
    border-radius: 8px;
    border: none;
}

.btn-primary {
    background-color: @primary-color;
    color: @white;
}
.btn-secondary {
    margin-top: 16px;
    background-color: rgba(7, 193, 96, 0.12);
    color: @primary-color;
}
</style>
